package main

import (
	"context"
	"fmt"
	"gitee.com/thingple/saturn/cmd/dashboard/ddd"
	"gitee.com/thingple/saturn/cmd/dashboard/process"
	"gitee.com/thingple/saturn/cmd/dashboard/static"
	"gitee.com/thingple/saturn/internal/broker"
	"gitee.com/thingple/saturn/internal/etc"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/mqtt"
	"github.com/lishimeng/go-log"
	"net/http"
	"time"
)

func main() {

	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()

	err := _main()
	if err != nil {
		fmt.Println(err)
	}
	time.Sleep(time.Millisecond * 500)
}

func _main() (err error) {
	application := app.New()

	err = application.Start(func(ctx context.Context, builder *app.ApplicationBuilder) error {

		var err error
		err = builder.LoadConfig(&etc.Config, nil)
		if err != nil {
			return err
		}

		broker.Init(ctx)

		builder.
			SetWebLogLevel("DEBUG").
			EnableWeb(etc.Config.Web.Listen, ddd.Router).
			EnableStaticWeb(func() http.FileSystem {
				return http.FS(static.Static)
			}).
			EnableMqtt(mqtt.WithRandomClientId(),
				mqtt.WithAuth(etc.Config.Mqtt.Username, etc.Config.Mqtt.Password),
				mqtt.WithBroker(etc.Config.Mqtt.Broker),
			).
			ComponentAfter(process.Setup).
			PrintVersion()
		return err
	}, func(s string) {
		log.Info(s)
	})

	return
}
